/*
 * Copyright 2010 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.mnit.basis.crypt.passwort;

import de.mnit.basis.crypt.JavaBase64;
import de.mnit.basis.crypt.digest.JAVA_DIGEST;
import de.mnit.basis.crypt.digest.JavaDigest;
import de.mnit.basis.daten.S_Vergleichbar;
import de.mnit.basis.fehler.Fehler;

/**
 * @author Michael Nitsche
 * 02.09.2007	Erstellt
 */
public class Passwort implements S_Vergleichbar<Passwort> {

	private final String hash;


	public Passwort(String pass) {
		this(pass, false);
	}

	public Passwort(String s, boolean hash) {
		Fehler.text.wenn_Null_o_Leer(s);
		this.hash = hash ? s : iBerechneHash(s);
	}


	public static Passwort neu(String pass) {
		return new Passwort(pass);
	}

	public static Passwort neu(String pass, boolean hash) {
		return new Passwort(pass, hash);
	}


	public boolean istGleich(Passwort passwort) {
		Fehler.objekt.wenn_Null(passwort);
		return this.hash.equals(passwort.toString());
	}

	public String toString() {
		return this.hash;
	}

	public boolean istGroesser(Passwort a) {
		throw Fehler.sonstige.da_Verboten();
	}

	public int compareTo(Passwort p) {
		throw Fehler.sonstige.da_Verboten();
	}

	// INTERN

	private String iBerechneHash(String pass) {
		JavaDigest jc=JavaDigest.neu(JAVA_DIGEST.SHA1);
		byte[] h=jc.berechnen(pass.getBytes());
		h=iXor(h, (byte)97);
		return "A"+JavaBase64.verschluesseln(h);
	}

	/**
	 * @copy CryptFunktionMN.xor
	 */
	private static byte[] iXor(byte[] b, byte zahl) {
		Fehler.objekt.wenn_Null(b,1);
		Fehler.zahl.wenn_Null(zahl);
		for(int i=0; i<b.length; i++)
			b[i]=(byte)(b[i]^zahl);
		return b;
	}

}
